package cn.bnjy.core;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;

/**
 * 描述：
 *
 * @since: 2018/11/21 22:40
 * @author: chavin
 */
@Component
@EnableScheduling
@Slf4j
public class ThreadAsyncConfigurer {

    @Value("${async.executor.thread.pool.core.size}")
    private int corePoolSize;
    @Value("${async.executor.thread.pool.max.size}")
    private int maxPoolSize;
    @Value("${async.executor.thread.queue.capacity}")
    private int queueCapacity;
    @Value("${async.executor.thread.name.prefix}")
    private String namePrefix;

    @Bean("taskExecutor")
    public Executor asyncServiceExecutor() {
        log.info("start asyncServiceExecutor");
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        threadPoolTaskExecutor.setThreadNamePrefix(namePrefix);
        // 当线程达到maxPoolSzie，用当前调用者线程执行
        // threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();
        log.info("end asyncServiceExecutor");
        return threadPoolTaskExecutor;
    }

}
